package quiz;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AcceptFriendServlet
 */
@WebServlet("/AcceptFriend")
public class AcceptFriendServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AcceptFriendServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DataBase db = (DataBase) request.getServletContext().getAttribute("db");
		Account curr = (Account) request.getSession().getAttribute("account");
		
		int friendID = Integer.parseInt(request.getParameter("friendID"));
		db.storeFriend(curr, db.getAccount(friendID));
		
		int messageID = Integer.parseInt(request.getParameter("messageID"));
		db.deleteMessage(messageID);
		
		//need to get all friend requests from the other person to the other
		ArrayList<Message> allMessages = db.getUserReceivedMessages(curr.getID());
		for (int i = 0; i < allMessages.size(); i++){
			if (allMessages.get(i).getType() == Message.REQUEST && allMessages.get(i).from.getID() == friendID){
				db.deleteMessage(allMessages.get(i));
			}
		}
		
		curr.checkAchievements(); //for the I'm so popular achievement
		
		//return to own profile - should change to go to friend's profile
		response.sendRedirect("Profile");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
